<!DOCTYPE html>
<html>
{include file="public/header" /}
<body>


<div class="layui-fluid" id="app">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">


            <form class="layui-form " action="">
                <input type="hidden" name="id" value="{$item.id}">

                <div class="layui-form-item">
                    <label class="layui-form-label">分类</label>
                    <div class="layui-input-block">
                        <select id="class_id" name="class_id" lay-verify="required" value="{$item.class_id}">
                            <option value=""></option>
                            {volist name="class_data" id="data"}
                            <option value={$data.id}>{$data.name}</option>
                            {/volist}
                        </select>
                    </div>
                </div>
                <script>
                    //设置选择状态
                    function setSelect(ele, val) {

                        $('#' + ele + ' option').each(function (index, ele) {

                            var el = $(ele);
                            if (el.attr('value') == val) {
                                el.attr('selected', 'selected')
                            } else {
                                el.removeAttr('selected');
                            }
                        })
                    }

                    $(function () {
                        setSelect('class_id', "{$item.class_id}")
                    });

                </script>

                <div class="layui-form-item">
                    <label class="layui-form-label">标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" value="{$item.title}" class="layui-input"
                               lay-verify="required">
                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label">缩略图片</label>

                    <div class="layui-input-inline " style="width: auto;">

                        <div class="layui-upload-drag" id="pic1" style="padding: 2px">
                            <img class="layui-upload-img"
                                 style="width: auto;height: 120px; object-fit: cover;"
                                 src="{$item.small_img2}">
                            <input type="hidden" name="small_img" value="{$item.small_img}">
                        </div>
                    </div>
                </div>


                <div class="layui-form-item" style="margin-bottom: 0px">

                    <div class="layui-inline">
                        <label class="layui-form-label">发布时间</label>
                        <div class="layui-input-inline" style="width: 150px;">
                            <input type="text" class="layui-input" id="time" name="create_time"
                                   value="{$item.create_time}"
                                   lay-verify="required">
                        </div>

                    </div>

                    <div class="layui-inline">
                        <label class="layui-form-label">点击量</label>
                        <div class="layui-input-inline" style="width: 100px;">
                            <input type="text" name="click_rate" value="{$item.click_rate}" class="layui-input"
                                   lay-verify="required">
                        </div>
                    </div>


                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label"></label>
                    <div class="layui-input-block">

                        <input type="checkbox" id="is_show" name="is_show" lay-skin="primary"
                               value="1"
                               title="展示"
                               {eq name="$item.is_show" value="1"}
                               checked
                               {else/}
                               {/eq}
                        >

                        <input type="checkbox" id="recommend" name="recommend" lay-skin="primary"
                               value="1"
                               title="推荐"
                               {eq name="$item.recommend" value="1"}
                               checked
                               {else/}
                               {/eq}
                        >


                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label">内容</label>
                    <div class="layui-input-block">
                        <div id="editor">

                        </div>
                    </div>
                </div>


                <div class="layui-form-item form-footer2">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="edit_article" >确认保存
                        </button>
                    </div>
                </div>


            </form>

        </div>


    </div>
</div>


<script>


    layui.use(['form', 'upload', 'laydate'], function () {
        var $ = layui.$
            , layer = layui.layer
            , form = layui.form;
        var upload = layui.upload;
        var laydate = layui.laydate;


        //网站设置
        //监听submit提交
        form.on('submit(edit_article)', function (obj) {
            //提交复选框选中的值
            var groupCheckbox_f=$("input[name='is_show']");
             console.log(groupCheckbox_f+'yyyyy');
            var is_show="";
            for(i=0;i<groupCheckbox_f.length;i++){
                if(groupCheckbox_f[i].checked){
                    var val =groupCheckbox_f[i].value;
                    if(is_show.length>0){
                        is_show+=","+val;
                    }else{
                        is_show+=val;
                    }

                }
            }
            var groupCheckbox_t=$("input[name='recommend']");
            var recommend="";
            for(i=0;i<groupCheckbox_t.length;i++){
                if(groupCheckbox_t[i].checked){
                    var val =groupCheckbox_t[i].value;
                    if(recommend.length>0){
                        recommend+=","+val;
                    }else{
                        recommend+=val;
                    }

                }
            }
            var text = editor.txt.html();
            obj.field['content']=text;
            obj.field['is_show']=is_show;
            obj.field['recommend']=recommend;
//            layer.msg(JSON.stringify(obj.field)); obj.field为当前容器的全部表单字段，名值对形式：{name: value}
            $.post("{:url('edit_article')}", obj.field, function (res) {

                if (res.code == 1) {

                    //将数据传入到父元素
                    parent.init();
                    parent.layer.closeAll();
                    parent.layer.msg(res.msg, {icon: 1})
                    $('#pic1 img').attr('src', '/res/img/thumb.png');
                    $('.layui-form')[0].reset();
                    return false;
                } else {
                    parent.layer.msg(res.msg, {icon: 2})
                    return false;
                }

            });
            return false;
        });


        //拖拽上传
        upload.render({
            elem: '#pic1'
            , url: '/tool/qiniu/upload'
            , before: function () {
                layer.load(2);
            }
            , done: function (res) {
                layer.closeAll();
                console.log(res)
                $('#pic1 img').attr('src', res.data.url);//完整url
                $('#pic1 input').val(res.data.pic);//存入数据库中的部分url
            }
        });
        //执行一个laydate实例
        laydate.render({
            elem: '#time' //指定元素
        });
    });

    //获取复选框选中的值
    var re = "{$item.is_show}";
    var check = re.split(",");
    var groupCheckbox_f = $("input[name='is_show']");
    $(function () {
        for (var i = 0; i < groupCheckbox_f.length; i++) {
            var val = groupCheckbox_f[i].value;
            if (check.indexOf(val) != -1) {
                groupCheckbox_f[i].checked = true;
            }
        }
    });
    var tt="{$item.recommend}";
    var check_t = tt.split(",");
    var groupCheckbox_t = $("input[name='recommend']");
    $(function () {
        for (var i=0;i<groupCheckbox_t.length;i++){
            var val =groupCheckbox_t[i].value;
            if (check_t.indexOf(val) != -1){
                groupCheckbox_t[i].checked = true;
            }
        }
    })
</script>



<script type="text/javascript" src="/static/js/wangEditor.min.js"></script>
<script type="text/javascript" src="/res/js/plupload/plupload.full.min.js"></script>
<script type="text/javascript" src="/res/js/plupload/i18n/zh_CN.js"></script>
<script type="text/javascript" src="/res/js/qiniu.js"></script>


<script>
    //    var E = window.wangEditor
    //    var editor = new E('#editor')
    //    editor.customConfig.debug = true
    //    // 配置服务器端地址
    //    //    editor.customConfig.uploadImgServer = "tool/qiniu/wang_upload";
    //    editor.customConfig.uploadImgShowBase64 = true
    //
    //    // 或者 var editor = new E( document.getElementById('editor') )
    //    editor.create();
    //    editor.customConfig.onchange = function (text) {
    //        var text = editor.txt.text();
    //    }


    var E = window.wangEditor
    var editor = new E('#editor')
    // 允许上传到七牛云存储
    editor.customConfig.qiniu = true
    editor.create()
    editor.txt.html('{$item.content}')

    //将编辑器内图片传至七牛云

    // 初始化七牛上传
    $.get('/tool/qiniu/get_config',{},function (res) {

        var domain=res.domain+'/';
        // 初始化七牛上传的方法
        function uploadInit() {
            // 获取相关 DOM 节点的 ID
            var btnId = editor.imgMenuId;
            var containerId = editor.toolbarElemId;
            var textElemId = editor.textElemId;

            // 创建上传对象
            var uploader = Qiniu.uploader({
                runtimes: 'html5,flash,html4',    //上传模式,依次退化
                browse_button: btnId,       //上传选择的点选按钮，**必需**
                uptoken_url: '/tool/qiniu/wang_uptoken',
                //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
                // uptoken : '<Your upload token>',
                //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
                // unique_names: true,
                // 默认 false，key为文件名。若开启该选项，SDK会为每个文件自动生成key（文件名）
                // save_key: true,
                // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
                domain: domain,
                //bucket 域名，下载资源时用到，**必需**
                container: containerId,           //上传区域DOM ID，默认是browser_button的父元素，
                max_file_size: '100mb',           //最大文件体积限制
                flash_swf_url: '/res/js/plupload/Moxie.swf',  //引入flash,相对路径
                filters: {
                    mime_types: [
                        //只允许上传图片文件 （注意，extensions中，逗号后面不要加空格）
                        { title: "图片文件", extensions: "jpg,gif,png,bmp" }
                    ]
                },
                max_retries: 3,                   //上传失败最大重试次数
                dragdrop: true,                   //开启可拖曳上传
                drop_element: textElemId,        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
                chunk_size: '4mb',                //分块上传时，每片的体积
                auto_start: true,                 //选择文件后自动上传，若关闭需要自己绑定事件触发上传
                init: {
                    'FilesAdded': function(up, files) {
                        plupload.each(files, function(file) {
                            // 文件添加进队列后,处理相关的事情
                            printLog('on FilesAdded');
                        });
                    },
                    'BeforeUpload': function(up, file) {
                        // 每个文件上传前,处理相关的事情
                        printLog('on BeforeUpload');
                    },
                    'UploadProgress': function(up, file) {
                        // 显示进度
                        printLog('进度 ' + file.percent)
                    },
                    'FileUploaded': function(up, file, info) {
                        // 每个文件上传成功后,处理相关的事情
                        // 其中 info 是文件上传成功后，服务端返回的json，形式如
                        // {
                        //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                        //    "key": "gogopher.jpg"
                        //  }
                        printLog(info);
                        // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html

                        var domain = up.getOption('domain');
                        var res = $.parseJSON(info);
                        var sourceLink = domain + res.key; //获取上传成功后的文件的Url

                        printLog(sourceLink);

                        // 插入图片到editor
                        editor.cmd.do('insertHtml', '<img src="' + sourceLink + '" style="max-width:100%;"/>')
                    },
                    'Error': function(up, err, errTip) {
                        //上传出错时,处理相关的事情
                        printLog('on Error');
                    },
                    'UploadComplete': function() {
                        //队列文件处理完毕后,处理相关的事情
                        printLog('on UploadComplete');
                    }
                    // Key 函数如果有需要自行配置，无特殊需要请注释
                    //,
                    // 'Key': function(up, file) {
                    //     // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
                    //     // 该配置必须要在 unique_names: false , save_key: false 时才生效
                    //     var key = "";
                    //     // do something with key here
                    //     return key
                    // }
                }
                // domain 为七牛空间（bucket)对应的域名，选择某个空间后，可通过"空间设置->基本设置->域名设置"查看获取
                // uploader 为一个plupload对象，继承了所有plupload的方法，参考http://plupload.com/docs
            });
        }
        uploadInit()
    });


    // 封装 console.log 函数
    function printLog(title, info) {
        window.console && console.log(title, info);
    }


</script>
